<template>
  <el-drawer :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item label="产品来源" prop="spuSource">
        <el-radio-group v-model="spuSource" :disabled="Boolean(formData.id)">
          <el-radio :value="0"> 手动输入产品信息 </el-radio>
          <el-radio :value="1"> 选择已有产品信息 </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="spuSource == 1" label="选择产品" prop="spuId">
        <SpuShowcase v-model="formData.spuId" :limit="1" @change="handleSpuChange" />
      </el-form-item>
      <el-form-item v-if="spuSource == 1 && formData.spuId" label="选择规格" prop="skuId">
        <div
          class="h-60px w-60px cursor-pointer"
          @click="handleSelectSku"
          :title="skuData.name || skuData.propertiesValue"
        >
          <div v-if="skuData && skuData.picUrl" class="select-box">
            <el-image :src="skuData.picUrl" />
          </div>
          <div v-else class="select-box" title="选择规格">
            <Icon icon="ep:plus" />
          </div>
        </div>
      </el-form-item>
      <el-form-item v-if="spuSource == 0 || formData.skuId" label="产品名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入产品名称" class="!w-240px" />
      </el-form-item>
      <el-form-item v-if="spuSource == 0 || formData.skuId" label="产品图片" prop="picUrl">
        <UploadImg v-model="formData.picUrl" height="80px" />
      </el-form-item>
      <el-form-item label="成本价" prop="costPrice">
        <el-input
          v-model="computedCostPrice"
          type="number"
          maxlength="8"
          :min="0"
          :max="99999999"
          :step="1"
          :precision="2"
          placeholder="请输入成本价"
          class="!w-240px"
          :disabled="spuSource == 1"
        >
          <template #suffix>
            <span>元</span>
          </template>
        </el-input>
        <el-text type="info">用于计算团购套餐的成本价</el-text>
      </el-form-item>
      <el-form-item label="单卖销售价" prop="originPrice">
        <el-input
          v-model="computedOriginPrice"
          type="number"
          maxlength="8"
          :min="0"
          :max="99999999"
          :step="1"
          :precision="2"
          placeholder="请输入单卖销售价"
          class="!w-240px"
          :disabled="spuSource == 1"
        >
          <template #suffix>
            <span>元</span>
          </template>
        </el-input>
        <el-text type="info">用于计算团购套餐的原价</el-text>
      </el-form-item>
      <el-form-item label="套卖销售价" prop="price">
        <el-input
          v-model="computedPrice"
          type="number"
          maxlength="8"
          :min="0"
          :max="99999999"
          :step="1"
          :precision="2"
          placeholder="请输入套卖销售价"
          class="!w-240px"
        >
          <template #suffix>
            <span>元</span>
          </template>
        </el-input>
        <el-text type="info">用于计算团购套餐的销售价</el-text>
      </el-form-item>
      <el-form-item label="套卖会员价" prop="vipPrice">
        <el-input
          v-model="computedVipPrice"
          type="number"
          maxlength="8"
          :min="0"
          :max="99999999"
          :step="1"
          :precision="2"
          placeholder="请输入套卖会员价，0表示免费"
          class="!w-240px"
        >
          <template #suffix>
            <span>元</span>
          </template>
        </el-input>
        <el-text type="info">用于计算团购套餐的会员价</el-text>
      </el-form-item>
      <el-form-item label="数量" prop="count">
        <el-input-number
          v-model="formData.count"
          type="number"
          maxlength="8"
          :min="1"
          :max="100"
          :step="1"
          :precision="0"
          placeholder="请输入数量"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item v-if="spuSource == 0" label="计价单位" prop="unit">
        <el-input
          v-model="formData.unit"
          placeholder="请输入计价单位，如：件、条、瓶"
          maxlength="8"
          class="!w-240px"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>
  <SkuTableSelect ref="skuTableSelectRef" :spu-id="formData.spuId" @change="handleSkuChange" />
</template>
<script setup lang="ts" name="PackageProductForm">
import * as GrouponProductApi from '@/api/mall/promotion/groupon/product'
import * as ProductSpuApi from '@/api/mall/product/spu'
import SpuShowcase from '@/views/mall/product/spu/components/SpuShowcase.vue'
import SkuTableSelect from '@/views/mall/product/spu/components/SkuTableSelect.vue'
import { fenToYuan, yuanToFen } from '@/utils'

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const spuSource = ref(0)
const formLoading = ref(false)
const formType = ref('')
const formData = ref<any>({
  id: undefined,
  packageId: undefined,
  name: undefined,
  picUrl: undefined,
  costPrice: 0,
  originPrice: 0,
  price: 0,
  vipPrice: 0,
  count: 1,
  unit: '件',
  spuId: undefined,
  skuId: undefined
})
const formRules = reactive({
  packageId: [{ required: true, message: '团购套餐编号缺失', trigger: ['blur', 'change'] }],
  spuSource: [
    {
      required: true,
      validator: (_rule: any, _value: any, callback: any) => {
        if (isNaN(Number(spuSource.value))) {
          callback(new Error('请选择产品来源'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ],
  spuId: [
    {
      required: true,
      validator: (_rule: any, _value: any, callback: any) => {
        if (spuSource.value != 1) {
          callback()
          return
        }
        if (!Boolean(formData.value.spuId)) {
          callback(new Error('请选择产品'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ],
  skuId: [
    {
      required: true,
      validator: (_rule: any, _value: any, callback: any) => {
        if (spuSource.value != 1) {
          callback()
          return
        }
        if (!Boolean(formData.value.skuId)) {
          callback(new Error('请选择产品规格'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ],
  name: [{ required: true, message: '赠品名称不能为空', trigger: ['blur', 'change'] }],
  picUrl: [{ required: true, message: '赠品图片不能为空', trigger: ['blur', 'change'] }],
  costPrice: [{ required: true, message: '成本价不能为空', trigger: ['blur', 'change'] }],
  originPrice: [{ required: true, message: '单卖销售价不能为空', trigger: ['blur', 'change'] }],
  price: [{ required: true, message: '套卖销售价不能为空', trigger: ['blur', 'change'] }]
})
const formRef = ref()

const open = async (type: string, packageId: number | string, id?: number | string) => {
  //console.log('type=' + type + ', packageId=' + packageId + ', id=' + id)
  dialogVisible.value = true
  dialogTitle.value = type == 'create' ? '加入团购产品' : '修改团购产品'
  formType.value = type
  resetForm()
  spuSource.value = 0
  if (id) {
    formLoading.value = true
    try {
      formData.value = await GrouponProductApi.getDetailById(id)
      if (formData.value.spuId) {
        spuSource.value = 1
        const spu = await ProductSpuApi.getSpu(formData.value.spuId)
        formData.value.name = spu.name
        formData.value.picUrl = spu.picUrl
        for (const sku of spu.skus!) {
          if (sku.id == formData.value.skuId) {
            handleSkuChange(sku)
            break
          }
        }
      }
    } finally {
      formLoading.value = false
    }
  }
  formData.value.packageId = packageId
}
defineExpose({ open })

const emit = defineEmits(['success'])
const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  formLoading.value = true
  try {
    const data = formData.value
    if (spuSource.value == 0) {
      // 直接输入赠品，则不关联产品
      data.spuId = undefined
      data.skuId = undefined
    }
    if (formType.value === 'create') {
      await GrouponProductApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await GrouponProductApi.updateById(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    packageId: undefined,
    name: undefined,
    picUrl: undefined,
    costPrice: 0,
    originPrice: 0,
    price: 0,
    vipPrice: 0,
    count: 1,
    unit: '件',
    spuId: undefined,
    skuId: undefined
  }
  formRef.value?.resetFields()
  skuData.value = {
    id: 0,
    name: '',
    picUrl: '',
    propertiesValue: ''
  }
}

const handleSpuChange = (spu: ProductSpuApi.Spu) => {
  formData.value.spuId = spu.id
  formData.value.name = spu.name
  formData.value.picUrl = spu.picUrl
}

const skuData = ref<any>({
  id: 0,
  name: '',
  picUrl: '',
  propertiesValue: ''
})
const skuTableSelectRef = ref()
const handleSelectSku = () => {
  skuTableSelectRef.value.open()
}
const handleSkuChange = (sku: ProductSpuApi.Sku) => {
  skuData.value = sku
  formData.value.skuId = sku.id
  if (!formData.value.id) {
    formData.value.costPrice = sku.costPrice
    formData.value.originPrice = sku.price
    formData.value.price = sku.price
    formData.value.vipPrice = sku.vipPrice
  }
  if (sku.name && sku.name.length && sku.name != '默认') {
    formData.value.name += ' ' + sku.name
  }
  if (sku.picUrl && sku.picUrl.length) {
    formData.value.picUrl = sku.picUrl
  }
}

const computedCostPrice = computed({
  get: () => Number(fenToYuan(formData.value.costPrice)),
  set: (newValue: number) => {
    formData.value.costPrice = yuanToFen(newValue)
  }
})
const computedOriginPrice = computed({
  get: () => Number(fenToYuan(formData.value.originPrice)),
  set: (newValue: number) => {
    formData.value.originPrice = yuanToFen(newValue)
  }
})
const computedPrice = computed({
  get: () => Number(fenToYuan(formData.value.price)),
  set: (newValue: number) => {
    formData.value.price = yuanToFen(newValue)
  }
})
const computedVipPrice = computed({
  get: () => Number(fenToYuan(formData.value.vipPrice)),
  set: (newValue: number) => {
    formData.value.vipPrice = yuanToFen(newValue)
  }
})
</script>
